package com.whfc.emp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.common.exception.BizException;
import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.file.properties.FileExpirationRules;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.FileUtil;
import com.whfc.common.util.PageUtil;
import com.whfc.emp.dao.AppFaceGateMapper;
import com.whfc.emp.dao.AppFaceGateVisitorMapper;
import com.whfc.emp.dto.AppFaceGateVisitorCheckDTO;
import com.whfc.emp.dto.AppFaceGateVisitorDTO;
import com.whfc.emp.dto.AppFaceGateVisitorNumDTO;
import com.whfc.emp.entity.AppFaceGate;
import com.whfc.emp.entity.AppFaceGateVisitor;
import com.whfc.emp.enums.AppVisitorsType;
import com.whfc.emp.enums.CheckResultState;
import com.whfc.emp.enums.VisitorState;
import com.whfc.emp.factory.AppFaceGateServiceFactory;
import com.whfc.emp.manager.FaceGateManager;
import com.whfc.emp.param.AppFaceGateVisitorAddParam;
import com.whfc.emp.param.AppFaceGateVisitorCheckAddParam;
import com.whfc.emp.param.AppFaceGateVisitorCheckParam;
import com.whfc.emp.service.AppFaceGateVisitorService;
import com.whfc.entity.dto.OssPathDTO;
import com.whfc.fuum.service.SysDeptService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @ClasssName AppFaceGateVisitorServiceImpl
 * @Description 闸机访客人员审核
 * @Author hw
 * @Date 2021/2/26 14:45
 * @Version 1.0
 */
@DubboService(interfaceClass = AppFaceGateVisitorService.class, version = "1.0.0", timeout = 5000)
public class AppFaceGateVisitorServiceImpl implements AppFaceGateVisitorService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppFaceGateVisitorMapper appFaceGateVisitorMapper;

    @Autowired
    private AppFaceGateServiceFactory appFaceGateServiceFactory;

    @Autowired
    private AppFaceGateMapper appFaceGateMapper;

    @DubboReference(interfaceClass = SysDeptService.class, version = "1.0.0")
    private SysDeptService sysDeptService;

    @Autowired
    private FilePathConfig msFilePathConfig;

    @Autowired
    private FileHandler fileHandler;

    @Override
    public AppFaceGateVisitorCheckDTO checkAdd(AppFaceGateVisitorCheckAddParam param) throws BizException {
        logger.info("访客校验信息是否存在,param:{}", param);
        AppFaceGateVisitor visitor = appFaceGateVisitorMapper.selectDayLaborerByOpenIdAndFaceGateId(param.getFaceGateId(), param.getOpenid());
        AppFaceGateVisitorCheckDTO dto = new AppFaceGateVisitorCheckDTO();
        dto.setCheck(false);
        Date now = new Date();
        if (visitor != null && VisitorState.success.getValue().equals(visitor.getState())
                && now.getTime() <= visitor.getEndTime().getTime()) {
            dto.setCheck(true);
        }
        dto.setOpenId(param.getOpenid());
        return dto;
    }

    @Override
    public void add(AppFaceGateVisitorAddParam param) throws BizException {
        logger.info("访客申请，param：{}", param);
        AppFaceGateVisitor visitor = new AppFaceGateVisitor();
        BeanUtils.copyProperties(param, visitor);
        appFaceGateVisitorMapper.insertSelective(visitor);
    }

    @Override
    public void del(Integer visitorId) throws BizException {
        logger.info("访客删除，visitorId：{}", visitorId);
        appFaceGateVisitorMapper.updateDelByVisitorId(visitorId);
    }

    @Override
    public void check(AppFaceGateVisitorCheckParam param) throws BizException {
        logger.info("访客审核，param：{}", param);
        Integer checkResult = param.getCheckResult();
        Integer visitorId = param.getVisitorId();
        AppFaceGateVisitor visitor = appFaceGateVisitorMapper.selectByPrimaryKey(visitorId);
        visitor.setCheckName(param.getCheckName());
        visitor.setCheckResult(checkResult);
        visitor.setState(checkResult);
        visitor.setCheckTime(new Date());
        visitor.setVisitorsType(param.getVisitorsType());
        if (AppVisitorsType.DAYLABORER.getValue().equals(param.getVisitorsType())) {
            Date now = new Date();
            Date starTime = DateUtil.getDateBegin(now);
            Date endTime = DateUtil.addDays(starTime, 2);
            visitor.setStartTime(starTime);
            visitor.setEndTime(endTime);
        }
        if (CheckResultState.SUCCESS.getValue().equals(checkResult)) {
            AppFaceGate faceGate = appFaceGateMapper.selectByPrimaryKey(visitor.getFaceGateId());
            if (faceGate == null) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "该闸机不存在");
            }
            FaceGateManager faceGateService = appFaceGateServiceFactory.getFaceGateService(faceGate.getId());
            String personGuid = faceGateService.deviceAuthorizationPerson(faceGate.getDeviceKey(), visitor.getName(), visitor.getPictureUrl());
            visitor.setRemark(personGuid);
        }
        appFaceGateVisitorMapper.updateByPrimaryKeySelective(visitor);
    }

    @Override
    public PageData<AppFaceGateVisitorDTO> list(Integer deptId, Integer pageSize, Integer pageNum, Integer state, Date startTime, Date endTime) throws BizException {
        logger.info("查询访客审批列表，deptId：{},pageSize：{},pageNum：{},state：{},startTime：{},endTime：{}", deptId, pageSize, pageNum, state, startTime, endTime);
        if (endTime != null) {
            endTime = DateUtil.getDateEnd(endTime);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<AppFaceGateVisitorDTO> list = appFaceGateVisitorMapper.selectBYDeptId(deptId, state, startTime, endTime);
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public AppFaceGateVisitorNumDTO getNum(Integer deptId, Date startTime, Date endTime) throws BizException {
        logger.info("查询访客状态数量，deptId：{},startTime：{},endTime：{}", deptId, startTime, endTime);
        List<AppFaceGateVisitorDTO> list = appFaceGateVisitorMapper.selectBYDeptId(deptId, null, startTime, endTime);
        Integer allNum = 0;
        Integer pendingNum = 0;
        Integer successNum = 0;
        Integer failNum = 0;
        AppFaceGateVisitorNumDTO numDTO = new AppFaceGateVisitorNumDTO();
        if (list != null && !list.isEmpty()) {
            allNum = list.size();
            for (AppFaceGateVisitorDTO appFaceGateVisitorDTO : list) {
                if (VisitorState.pending.getValue().equals(appFaceGateVisitorDTO.getState())) {
                    pendingNum++;
                } else if (VisitorState.success.getValue().equals(appFaceGateVisitorDTO.getState())) {
                    successNum++;
                } else if (VisitorState.fai.getValue().equals(appFaceGateVisitorDTO.getState())) {
                    failNum++;
                }
            }
        }
        numDTO.setAllNum(allNum);
        numDTO.setFailNum(failNum);
        numDTO.setSuccessNum(successNum);
        numDTO.setPendingNum(pendingNum);
        return numDTO;
    }

    @Override
    public OssPathDTO export(Integer deptId, Integer state, Date startTime, Date endTime) {
        logger.info("导出访客审批列表,deptId：{}，startTime：{}，endTime：{}", deptId, startTime, endTime);
        List<AppFaceGateVisitorDTO> list = appFaceGateVisitorMapper.selectBYDeptId(deptId, state, startTime, endTime);
        String deptName = sysDeptService.getDeptNameById(deptId);
        OssPathDTO ossPathDTO = new OssPathDTO();
        try {
            // 获取模板
            ClassPathResource resource = new ClassPathResource("templates/faceGateVisitor.xls");
            InputStream templateFileInputStream = resource.getInputStream();
            File tempFile = FileUtil.copyTemplateFile(templateFileInputStream);

            //写数据
            FileInputStream fileInputStream = new FileInputStream(tempFile);
            HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
            HSSFSheet sheet = workbook.getSheetAt(0);
            HSSFRow row0 = sheet.getRow(0);
            HSSFCell cell0 = row0.getCell(0);
            cell0.setCellValue(String.format("%s 访客审批记录", deptName));
            int rowIdx = 2;
            for (AppFaceGateVisitorDTO appFaceGateVisitorDTO : list) {
                HSSFRow row1 = sheet.createRow(rowIdx);
                row1.createCell(0).setCellValue(appFaceGateVisitorDTO.getName());
                row1.createCell(1).setCellValue(appFaceGateVisitorDTO.getPhone());
                row1.createCell(2).setCellValue(appFaceGateVisitorDTO.getFaceGateName());
                row1.createCell(3).setCellValue(appFaceGateVisitorDTO.getRemark());
                row1.createCell(4).setCellValue(DateUtil.formatDate(appFaceGateVisitorDTO.getCreateTime(), DateUtil.DATE_TIME_FORMAT));
                row1.createCell(5).setCellValue(VisitorState.parseByValue(appFaceGateVisitorDTO.getState()));
                row1.createCell(6).setCellValue(appFaceGateVisitorDTO.getCheckName());
                if (appFaceGateVisitorDTO.getCheckTime() != null) {
                    row1.createCell(7).setCellValue(DateUtil.formatDate(appFaceGateVisitorDTO.getCheckTime(), DateUtil.DATE_TIME_FORMAT));
                }
                rowIdx++;
            }
            FileOutputStream fos = new FileOutputStream(tempFile);
            workbook.write(fos);
            fos.flush();
            fos.close();
            //上传oss

            String name = msFilePathConfig.getFilePath("emp/tmp", String.format("%s访客导出列表.xls", deptName));
            FileInputStream inputStream = new FileInputStream(tempFile);
            String upload = fileHandler.upload(name, inputStream, FileExpirationRules.oneDay);
            ossPathDTO.setPath(upload);
        } catch (Exception e) {
            logger.error("导出访客审批列表失败", e);
        }
        return ossPathDTO;
    }

    @Override
    public AppFaceGateVisitorDTO getByDeviceKeyAndGuid(String deviceKey, String personGuid) {
        return appFaceGateVisitorMapper.getByDeviceKeyAndGuid(deviceKey,personGuid);
    }
}
